package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.bean.User;
import com.itheima.common.R;
import com.itheima.service.UserService;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 生成验证码，并发送给用户
      * @param user 使用user接收phone
     * @return
     */
    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody User user, HttpSession httpSession){
        String phone = user.getPhone();
        //1.生成随机的验证码
        String code = ValidateCodeUtils.generateValidateCode4String(4);
        //2.发送验证码到用户
        System.out.println(code);
        //SMSUtils.sendMessage("瑞吉外卖","SMS_298425151",phone,code);
        //3.将phone与code对应起来，并储存(后面要做校验)
        httpSession.setAttribute(phone,code);

        return R.success("已发送验证码");
    }

    /**
     *
     * @param map 使用map做实体类接收json
     * @param httpSession 获取存起来的phone:code  与传进来的code做校验
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map,HttpSession httpSession){
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();

        String codeInSession = httpSession.getAttribute(phone).toString();

        //codeInSession可能为空：没有获取验证码就登录
        if(codeInSession!=null&&codeInSession.equals(code)){
            //1.通过手机号查询用户
            User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getPhone, phone));
            //2.没注册就insert  注册了就行
            if(user==null){
                user=new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            httpSession.setAttribute("user",user.getId());
            //返回一个用户，因为移动端也要保存一个用户
            return R.success(user);
        }

        return R.error("登录失败");
    }
}
